package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PasswordDialog extends Activity {
	private EditText mPass;
	private String mHash;
	private Intent i;
	private int mTryCount;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Enter your password:");
		setContentView(R.layout.password);
		
		// check if user has protected program with a password
        BuxoidDb db = new BuxoidDb(this);
        db.open();
        mHash = db.getSetting(BuxoidDb.SETTING_BUXOID_PASS);
        db.close();
        
        i = new Intent(this, Buxoid.class);
        
        if (mHash.length() > 0) {
	        mTryCount = 0;
			
			mPass = (EditText) findViewById(R.id.password);
			Button ok = (Button) findViewById(R.id.password_ok);
			Button cancel = (Button) findViewById(R.id.password_cancel);
			
			ok.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					if (mHash.equals(Buxoid.getMd5Hash(mPass.getText().toString()))) {
						startActivity(i);
						finish();
					} else {
						if (++mTryCount == 3) {
							Toast.makeText(PasswordDialog.this, "Password did not match. Exiting...", Toast.LENGTH_SHORT).show();
							finish();
						} else {
							Toast.makeText(PasswordDialog.this, "Password did not match.", Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			
			cancel.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					finish();
				}
			});
        } else {
        	// the user has not set a password, so start the program
        	startActivity(i);
        	finish();
        }
	}
}
